#include "writer.h"
#include <QtTest/QTest>

Writer::Writer(Shelf *shelf, int time, QObject *parent) :
    shelf(shelf), time(time), QObject(parent)
{
}

void Writer::run(){
    int action, pos;

    while(true){
        action = qrand() % 2;
        switch(action){
            case 0:
                //--- write
                pos = shelf->tryWriteNewBook();
                if(pos != -1) {
                    emit write();
                    QTest::qSleep(time*1000);
                    shelf->putNewBook(pos);
                    bookCollection.push_back(pos);
                }
                break;
            case 1:
                //--- edit
                if(bookCollection.size() == 0) continue;
                pos = qrand() % bookCollection.size();
                emit wait();
                shelf->takeBook(pos);
                emit edit();
                QTest::qSleep(time*1000);
                shelf->putBook(pos);
                break;
        }
    }
}

